<template>
  <div class="sys-org-container">

    <div style="width: 100%;">
      <screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData">
        <el-button type="primary" icon="ele-Plus" @click="openAddOrg">
          新增
        </el-button>
        <el-button type="primary" @click="exportExcel">
          导出
        </el-button>
      </screeningCondition>
    </div>
    <!-- 列表展示 -->
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.Data" class="el-table" v-loading="state.loading" row-key="id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border highlight-current-row
        @current-change="handleRowChange"
        :header-cell-style="{ background: 'var(--el-color-primary)', height: '55px', color: '#fff', border: '1px solid #fff', fontWeight: 'bold', fontSize: '13px', }"
        :cell-style="{ padding: '2px' }" @select="getRows" ref="tableRef">
        <el-table-column type="selection" align="center" width="40"></el-table-column>
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="regionStatus" label="状态" align="center" width="70">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.regionStatus == 0">启用</el-tag>
            <el-tag type="danger" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="regionNum" label="区域编号" width="120" align="center" show-overflow-tooltip /> -->
        <el-table-column prop="regionName" label="区域名称" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="totalStorage" label="库位总数" width="70" align="center" show-overflow-tooltip />
        <el-table-column prop="enabledStorage" label="可用库位" align="center" width="70" show-overflow-tooltip />
        <el-table-column prop="usedStorage" label="已占用库位" align="center" width="90" show-overflow-tooltip />
        <!-- <el-table-column prop="whNum" label="所属仓库" align="center" show-overflow-tooltip /> -->
        <el-table-column prop="whName" label="所属仓库" align="center" show-overflow-tooltip />
        <el-table-column label="绑定物料" align="center" show-overflow-tooltip>
          <template v-slot="scope">
            <span v-if="scope.row.regionMaterielNum">{{ scope.row.regionMaterielNum + '(' + scope.row.materielName + ')'
              }}</span>
            <span v-else>暂未绑定</span>
          </template>
        </el-table-column>
        <el-table-column prop="remake" label="备注" header-align="center" show-overflow-tooltip />
        <el-table-column prop="createUserName" label="新增人" align="center" width="100" show-overflow-tooltip />
        <el-table-column prop="updateUserName" label="更新人" align="center" width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="240" fixed="right" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEdit(scope.row)" v-auth="'sysOrg:update'">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-auth="'region:delete'">
              删除
            </el-button>
            <el-button size="small" type="warning" @click="handleOpenRelation(scope.row)" v-auth="'sysOrg:update'">
              库位管理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.pageSize"
        :page-sizes="[5, 30, 40, 50]" layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
    </el-card>



    <!-- <el-drawer v-model="editDrawer" title="修改区域" :append-to-body="true" size="30%" >
      <el-form :model="state.ruleForm2" ref="editRuleFormRef" label-width="auto" class="fl">
        <el-form-item label="编号">
          <el-input v-model="state.ruleForm2.regionNum" placeholder="区域编号" clearable class="input" disabled />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionName"
          :rules="[{ required: true, message: '区域名称不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm2.regionName" placeholder="名称" clearable class="input" />
        </el-form-item>

        <el-form-item label="状态" prop="regionStatus"
          :rules="[{ required: true, message: '区域状态不能为空', trigger: 'blur' }]">
          <el-radio-group v-model="state.ruleForm2.regionStatus" class="ml-4">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属仓库" prop="whNum" :rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm2.whNum" filterable clearable class="w100">
            <el-option v-for="item in state.wareHouseNames" :key="item" :label="item.eg_wms_warehouse.WHName"
              :value="item.eg_wms_warehouse.WHNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定物料" prop="regionMaterielNum">
          <el-select v-model="state.ruleForm2.regionMaterielNum" filterable clearable class="w100">
            <el-option v-for="item in state.materialList" :key="item" :label="item.materielName"
              :value="item.materielNum" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="state.ruleForm2.regionRemake" placeholder="请输入备注内容" clearable type="textarea"
            class="extra" />
        </el-form-item>
      </el-form>
      <el-form-item>
        <div style="margin: 40px auto">
          <el-button @click="handleEdit" type="primary" round style="width: 80px; height: 30px">提交</el-button>
          <el-button round style="width: 80px; height: 30px">取消</el-button>
        </div>
      </el-form-item>
    </el-drawer>

    <el-drawer v-model="addDrawer" title="新增区域" :append-to-body="true" size="30%">
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" class="fl">
        <el-form-item label="区域名称" prop="regionName"
          :rules="[{ required: true, message: '区域名称不能为空', trigger: 'blur' }]">
          <el-input v-model="state.ruleForm.regionName" placeholder="名称" clearable class="input" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="whNum" :rules="[{ required: true, message: '所属仓库不能为空', trigger: 'blur' }]">
          <el-select v-model="state.ruleForm.whNum" filterable clearable class="w100">
            <el-option v-for="item in state.wareHouseNames" :key="item" :label="item.eg_wms_warehouse.WHName"
              :value="item.eg_wms_warehouse.WHNum" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定物料">
          <el-select v-model="state.ruleForm.regionMaterielNum" filterable clearable class="w100">
            <el-option v-for="item in state.materialList" :key="item.materielNum" :label="item.materielName"
              :value="item.materielNum" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="regionStatus"
          :rules="[{ required: true, message: '区域状态不能为空', trigger: 'blur' }]">
          <el-radio-group v-model="state.ruleForm.regionStatus" class="ml-4">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="state.ruleForm.regionRemake" placeholder="请输入备注内容" clearable type="textarea"
            class="extra" />
        </el-form-item>
      </el-form>
      <el-form-item>
        <div style="margin: 60px auto">
          <el-button @click="handleAdd" type="primary" round style="width: 80px; height: 30px">提交</el-button>
          <el-button @click="addDrawer = false" round style="width: 80px; height: 30px">取消</el-button>
        </div>
      </el-form-item>
    </el-drawer> -->
    <!-- 
    <formDrawer ref="formDrawerRef2" title="关联库位" size="80%" direction="ttb">
      <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
        <el-tag type="success" size="large">{{ state.ruleForm2.regionName }}</el-tag>
        <el-button type="primary" icon="ele-Plus" @click="handleAllStorageOpen()" v-auth="'sysOrg:add'"
          style="margin-left: 20px;"> 新增
        </el-button>
        </el-form-item>
        </el-form> 
        当前库位信息列表 
        <el-table :data="state.currentChildrenData" style="width: 100%" v-loading="state.loading" row-key="id"
          default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border>
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column type="index" width="40" align="center"></el-table-column>
          <el-table-column prop="storageNum" label="库位编号" align="center" show-overflow-tooltip />
          <el-table-column prop="storageName" label="库位名称" header-align="center" align="center" show-overflow-tooltip />
          <el-table-column prop="storageOccupy" label="占用" width="70" align="center" show-overflow-tooltip>
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.storageOccupy == 0">未占用</el-tag>
              <el-tag type="danger" v-else-if="scope.row.storageOccupy == 1">已占用</el-tag>
              <el-tag type="danger" v-else>预占用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="storageStatus" label="库位状态" width="70" align="center" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.storageStatus === 0">启用</el-tag>
              <el-tag type="danger" v-else>停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right" align="center" show-overflow-tooltip>
            <template #default="scope">
              <el-button icon="ele-Edit" size="small" text type="primary" v-auth="'sysOrg:delete'">
                删除
              </el-button>
            </template>
          </el-table-column>
         </el-table>
      </el-card>
      <el-pagination v-model:current-page="state.queryParams2.page" v-model:page-size="state.queryParams2.pageSize"
        :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="state.totalTwo"
        @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :small="true" />
      <div style="width: 100%; height: 30px; margin-top: 40px">
        <el-button @click="handleCancel" type="primary" round
          style="width: 80px; height: 30px; margin: 0 auto; display: block">确认</el-button>
      </div>
    </formDrawer>
    <所有的库位信息列表
    <el-drawer v-model="innerDrawer" title="库位关联" :append-to-body="true" size="80%" direction="ttb">
      <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
        <el-form :model="state.queryParams" ref="queryForm" :inline="true">
          <el-form-item label="名称">
            <el-input v-model="state.queryParams2.storageName" placeholder="库位名称" clearable />
          </el-form-item>
          <el-form-item label="编号">
            <el-input v-model="state.queryParams2.storageNum" placeholder="库位编码" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio v-model="state.queryParams2.storageStatus" :label="0">启用</el-radio>
            <el-radio v-model="state.queryParams2.storageStatus" :label="1">禁用</el-radio>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="ele-Search" @click="handleAllQuery" v-auth="'sysOrg:list'"
              style="margin-left: 50px;">
              查询 </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="full-table" shadow="hover" style="margin-top: 8px">
        <el-table :data="state.allLocationData" style="width: 100%" row-key="id" default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border @select="selectionLineChangeHandle"
          ref="multipleTableRef">
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="regionName" label="区域名称" header-align="center" align="center" show-overflow-tooltip />
          <el-table-column prop="storageNum" label="库位编号" align="center" show-overflow-tooltip />
          <el-table-column prop="storageName" label="库位名称" header-align="center" align="center" show-overflow-tooltip />
          <el-table-column prop="id" label="占用情况" align="center" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.storageOccupy == 0">未占用</el-tag>
              <el-tag type="danger" v-else-if="scope.row.storageOccupy == 1">已占用</el-tag>
              <el-tag type="danger" v-else>预占用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="库位状态" width="70" align="center" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.storageStatus === 0">启用</el-tag>
              <el-tag type="danger" v-else>停用</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-pagination v-model:current-page="state.queryParams3.page" v-model:page-size="state.queryParams3.pageSize"
        :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="state.totalThree"
        @size-change="handleSizeChange2" @current-change="handleCurrentChange2" :small="true" />
      <div style="width: 100%;display: flex;justify-content: flex-end;padding: 30px;">
        <el-button @click="handleChange" type="primary" round style="width:80px;height:30px">确认</el-button>
        <el-button @click="innerDrawer = false" round style="width:80px;height:30px">取消</el-button>
      </div>
    </el-drawer> -->
    <!-- 增删组件 -->
    <EditPos ref="editPosRef" :title="state.editPosTitle" @handleQuery="getData" />
    <!-- 批量移动库位功能 -->
    <StorageManage ref="storageRef" :regionName="state.ruleForm.regionName" :regionNum="state.ruleForm.regionNum"
      @refresh="getData"></StorageManage>
  </div>
</template>
<script lang="ts" setup name="region">
import { nextTick, onMounted, reactive, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { WmsApi } from "/@/api/wh";
import { feature } from "/@/utils/axios-utils";
import { getAPI } from "/@/utils/axios-utils";
import screeningCondition from "/@/views/tools/screeningCondition.vue";
import EditPos from '/@/views/system/area/component copy/editPos.vue';
import StorageManage from '/@/views/system/area/component copy/storageManage.vue';
import { APIJSONApi } from "/@/api-services/apis/apijsonapi";
import json2Excel from "/@/utils/json2Excel.ts";


// key -> name 的映射
const excelKeyToName = {
  regionName: "名称",
  whName: "仓库",
  materielName: "绑定物料",
  remake: "备注",
  totalStorage: "库位总数",
  enabledStorage: "可用库位",
  usedStorage: '已占用库位'
};
// 子组件对象
const storageRef = ref()
const editPosRef = ref()
const tableRef = ref()
//当前行高亮
const currentRow = ref();
const state = reactive({
  editPosTitle: '',
  loading: false,
  //区域数据列表数据
  Data: [],
  queryParams: {
    regionNum: '',
    regionName: '',
    page: 1,
    pageSize: 20,
  },
  //下拉选择的仓库名
  wareHouseNames: [],
  //勾选要移动的区域
  dataonLineListSelections: [],
  //新增内容收集的对象
  ruleForm: {},
  //修改内容收集的对象
  ruleForm2: {},
  //所有库位数据
  allLocationData: [],
  //当前库位数据
  currentChildrenData: [],
  total: 0,
  //筛选框里的内容
  inquireInfo: [
    {
      label: "区域编号",
      value: "",
      key: "regionNum",
      options: [],
      type: "input",
    },
    {
      label: "区域名称",
      value: "",
      key: "regionName",
      options: [],
      type: "input",
    },
    {
      label: "仓库名称",
      value: "",
      key: "whName",
      options: [],
      type: "input",
    },

  ],
  value: {},
  //勾选导出的数据
  selections: [],
  //勾选数据后才进行导出
  tickData: false
});
onMounted(
  //获取下拉选择的仓库名数据
  async () => {
    try {
      const res = await feature(
        getAPI(APIJSONApi).apiAPIJSONGetPost({
          "[]": {
            "eg_wms_warehouse": {
              IsDelete: 0,
              "@column": "WHName,WHNum",
            },
          },
        })
      );
      console.log(res);

      state.wareHouseNames = res[1].data.result["[]"];
    } catch (error) {
      console.log(error);
    }
    //获取下拉物料列表
    await WmsApi()
      .MaterielPagePost({
        page: 0,
        pageSize: 100,
      })
      .then(function (res) {
        state.materialList = res.data.result.items;
        console.log(state.materialList);
      })
      .catch(function (error) {
        console.log(error);
      });
    getData(state.queryParams)
  });

const getRows = (selection, row) => {
  console.log(selection);
  state.selections = selection
  console.log(row);
  state.tickData = true;

}
// 导出 Excel 文件
const exportExcel = () => {
  // 格式化参数
  let exportData

  if (state.tickData) {
    exportData = state.selections
  } else {
     exportData = state.Data
  }
  const data = exportData.map((item) => {
    const newItem: any = {};
    Object.keys(item).forEach(key => {
      //如果当前key存在在映射对象中的话
      if (excelKeyToName.hasOwnProperty(key)) {
        newItem[excelKeyToName[key]] = item[key];
      } else {
        return;// 跳过当前迭代 
      }

    });
    return newItem;
  });

  // 导出 Excel
  json2Excel(data);
};
// 打开新增页面
const openAddOrg = () => {
  state.editPosTitle = '添加新区域';
  editPosRef.value?.openDialog({ regionStatus: 0 });
};

// 打开编辑页面
const openEdit = (row: any) => {
  state.editPosTitle = '编辑区域';
  editPosRef.value?.openDialog(row);
};

const getData = (value: any) => {
  state.value = value;
  let params = {
    page: state.queryParams.page,
    pageSize: state.queryParams.pageSize,
    regionNum: value?.regionNum ?? null,
    regionName: value?.regionName ?? null,
    whName: value?.whName ?? null
  };
  WmsApi()
    .RegionPagePost(params)
    .then(function (res) {
      state.Data = res.data.result.items;
      state.total = res.data.result.total;

    })
    .catch(function (error) {
      console.log(error);
    });
}


//打开库位绑定页面
const handleOpenRelation = (row) => {
  state.ruleForm.regionName = row.regionName

  state.ruleForm.regionNum = row.regionNum
  console.log(state.ruleForm.regionNum);
  // 等待下一次 DOM 更新刷新的工具方法。
  nextTick(() => {
    storageRef.value?.openDialog(row);
  });
};

const handleSizeChange = (val) => {
  state.queryParams.pageSize = val;
  state.queryParams.regionNum = state.value?.regionNum;
  state.queryParams.regionName = state.value?.regionName;
  state.queryParams.whName = state.value?.whName
  getData(state.queryParams)
};
const handleCurrentChange = (newVal) => {
  state.queryParams.page = newVal;
  state.queryParams.regionNum = state.value?.regionNum;
  state.queryParams.regionName = state.value?.regionName;
  state.queryParams.whName = state.value?.whName
  getData(state.queryParams)
};
//高亮当前行
const handleRowChange = (val) => {
  currentRow.value = val;
};
//删功能
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除该区域：【${row.regionName}】?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await WmsApi()
        .RegionPageDelete(row.id)
        .then(function (res) {
          ElMessage.success("删除成功");
          getData(state.queryParams)
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

</script>
<style lang="scss" scoped>
.lie .el-form-item {
  margin-bottom: 30px;
  font-size: 16px;
}

.fl {
  /* padding: 20px; */
  width: 60%;
  margin: 20px 80px;
}

.hang {
  display: flex;
}

.radius {
  height: 22px;
  width: 164.75px;
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
  background-color: #ddd;
  padding-left: 5px;
  padding-top: -4px;
  color: #afabb9;
  background-color: #f5f7fa;
  margin-top: 20px;
}




.container {
  margin-top: 15px;
  width: 100%;
  display: flex;
  flex-direction: column;
  height: calc(100% - 82px);
}

.table {
  width: 100%;
  flex: 1;
  height: 100%;
}

.el-table {
  width: 100%;

  /* overflow: auto; */
}
</style>